import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';
import { h } from 'vue';

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query);
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('StockRecord:Export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData());
                        }
                    },
                    add: {
                        show: auth('StockRecord:Create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 200,
                buttons: {
                    view: {
                        type: 'text',
                        order: 1,
                        show: auth('StockRecord:Retrieve')
                    },
                    edit: {
                        type: 'text',
                        order: 2,
                        show: auth('StockRecord:Update')
                    },
                    copy: {
                        type: 'text',
                        order: 3,
                        show: auth('StockRecord:Copy')
                    },
                    remove: {
                        type: 'text',
                        order: 4,
                        show: auth('StockRecord:Delete')
                    },
                },
            },
            columns: {
                material: {
                    title: '原材料',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        url: '/api/material/',
                        value: 'id',
                        label: 'name',
                        immediate: true,
                        prototype: false,
                        cache: false,
                        async onReady({ dict }) {
                            await dict.loadDict();
                        }
                    }),
                    column: {
                        minWidth: 120,
                        formatter: ({ row }: { row: any }) => {
                            if (row.material && typeof row.material === 'object') {
                                return row.material.name;
                            } 
                            return dict({
                                url: '/api/material/',
                                value: 'id',
                                label: 'name'
                            }).getLabel(row.material);
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '原材料必选' }],
                        component: {
                            placeholder: '请选择原材料',
                            filterable: true,
                            clearable: true,
                        },
                        valueBuilder({ form, row }) {
                            if (row && row.material) {
                                if (typeof row.material === 'object') {
                                    form.material = row.material.id;
                                }
                            }
                        },
                        valueResolve({ form, key, value }) {
                            if (key === 'material' && value && typeof value === 'object') {
                                form.material = value.id || value;
                            }
                        }
                    },
                    viewForm: {
                        component: {
                            name: 'fs-dict-select',
                            readonly: true
                        }
                    },
                },
                record_type: {
                    title: '记录类型',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: 'in', label: '入库' },
                            { value: 'out', label: '出库' },
                            { value: 'check', label: '盘点' },
                        ]
                    }),
                    column: {
                        minWidth: 100,
                        formatter: ({ row }: { row: any }) => {
                            const typeMap: Record<string, { text: string; type: string }> = {
                                'in': { text: '入库', type: 'success' },
                                'out': { text: '出库', type: 'danger' },
                                'check': { text: '盘点', type: 'info' }
                            };
                            const type = typeMap[row.record_type] || { text: row.record_type, type: 'default' };
                            return <el-tag size="small" type={type.type}>{type.text}</el-tag>;
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '记录类型必选' }],
                        component: {
                            placeholder: '请选择记录类型',
                        },
                    },
                },
                quantity: {
                    title: '数量',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 100,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '数量必填' }],
                        component: {
                            placeholder: '请输入数量',
                            precision: 0,
                            step: 1,
                            min: 1,
                            controlsPosition: 'right',
                            onChange: (value: number) => {
                                return Math.floor(Number(value));
                            }
                        },
                    },
                },
                before_quantity: {
                    title: '操作前库存',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        show: false,
                    },
                },
                after_quantity: {
                    title: '操作后库存',
                    type: 'number',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        show: false,
                    },
                },
                remark: {
                    title: '备注',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入备注信息',
                            rows: 3,
                        },
                    },
                },
            },
            form: {
                beforeSubmit({ form }) {
                    // 移除非本表单的判断逻辑
                    return true;
                },
                afterSubmit() {
                    // 提交表单后自动刷新列表
                    crudExpose.doRefresh();
                }
            },
        },
    };
} 